<?php

/**
 * @name NoticeController
 * @desc 控制器
 */
class NoticeController extends AdminCommonController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        echo "Hello sysconfig";
        return false;
    }

    //公告列表
    public function listAction(){

        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $noticeModel = NoticeModel::getSingleton();
        $list = $noticeModel->db
            ->where([])
            ->order('id desc')
            ->limit(($page - 1) * $row, $row)
            ->select();
        $total = $noticeModel->db
            ->where([])
            ->count();

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //增加公告
    public function addAction(){
        $params = $this->jsonData();

        $rule = [
            'title'     => 'require',
            'content'   => 'require|length:1,255',
            'is_show'   => 'require|in:0,1',
        ];
        $msg = [
            'title.require' => '必须输入标题',
            'content.require'   => '必须输入公告内容',
            'content.length'  => '公告内容须小于255个字符'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $params['create_user_id'] = $this->admin_info['admin_id'];
        $noticeModel = NoticeModel::getSingleton();
        if(!$noticeModel->add($params)){
            $this->ajaxReturn(400, '添加失败');
        }

        $this->ajaxReturn(0, '添加成功');
    }

    //修改公告
    public function editAction(){
        $params = $this->jsonData();

        if(!$params || empty($params) || !isset($params['id'])){
            $this->ajaxReturn(400, '修改失败');
        }

        $noticeModel = NoticeModel::getSingleton();
        $res = $noticeModel->update(['id'=> $params['id']],
            ['title'=> $params['title'], 'content'=> $params['content'], 'is_show'=> $params['is_show'],'update_time'=> time()]
        );

        if(!$res){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }
}
